import logging
from datetime import datetime
from typing import Optional

import requests
import pandas as pd
from django.conf import settings

from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from search_main.utlis import TimeUtils
from search_main.utlis import HttpClient
from search_main.utlis import token_51cto
from search_main.models import Hot51CTO
from search_main.serializers import Hot51CTOSerializer


class ViewsCsdn(APIView, TimeUtils):

    def __init__(self):
        super().__init__()
        self.http_client = HttpClient()
        self.timestamp = self.get_timestamp()
        self.token = token_51cto.get_token()

    def get(self, request):
        try:
            page = request.query_params.get('page', 1)
            page_size = request.query_params.get('page_size', 30)
            params = {
                'page': page,
                'pageSize': page_size,
            }
            response = self.http_client.get_client(
                url=settings.API_CSDN_URL,
                params=params,
            )
            raw_data = response['data']
            items = raw_data.get("data", [])

            processed_data = []
            for item in items:
                processed_data.append({
                    "id": item.get("productId", ""),
                    "title": item.get("articleTitle", ""),
                    "cover": (item.get("picList") or [""])[0] if item.get("picList") else "",
                    "author": item.get("nickName", ""),
                    "timestamp": self.parse_time(item.get("period")[:-3]),
                    "hot": self._parse_hot_score(item.get("hotRankScore")),
                    "url": item.get("articleDetailUrl", ""),
                    "mobile_url": item.get("articleDetailUrl", "")
                })
            result = {
                "name": "csdn",
                "title": "CSDN",
                "type": "排行榜",
                "description": "专业开发者社区",
                "link": "https://www.csdn.net/",
                "total": len(processed_data),
                "data": processed_data,
                "update_time": self.format_time()
            }

            # =================
            print(f"CSDN热榜（共{result['total']}条）:")
            for idx, item in enumerate(processed_data[:10], 1):
                print(f"{idx}. [{item['timestamp']}] {item['title']}")
                print(f"   作者：{item['author']} | 热度：{item['hot']}")
                print(f"   链接：{item['url']}\n")
            # =================

            return Response(result, status=status.HTTP_200_OK)
        except requests.exceptions.RequestException as e:
            print(f"请求失败: {e}")
            return Response(
                {"error": "服务暂不可用"},
                status=status.HTTP_503_SERVICE_UNAVAILABLE
            )

    def _parse_hot_score(self, score: str) -> Optional[int]:
        """转换热度分数"""
        try:
            return int(float(score)) if score else None
        except (ValueError, TypeError):
            return None
